package com.lightjet.macross.base.awf.service.impl;

import com.lightjet.macross.base.awf.service.AWFEventListener;
import io.netty.util.internal.StringUtil;
import lombok.extern.java.Log;
import org.activiti.engine.delegate.event.ActivitiEvent;
import org.activiti.engine.delegate.event.ActivitiEventType;
import org.activiti.engine.delegate.event.impl.ActivitiEntityEventImpl;
import org.activiti.engine.delegate.event.impl.ActivitiEventBuilder;
import org.activiti.engine.impl.context.Context;
import org.activiti.engine.impl.persistence.entity.ExecutionEntity;
import org.activiti.engine.impl.persistence.entity.TaskEntity;
import org.activiti.engine.runtime.Execution;

import java.util.ArrayList;

@Log
public class TaskCreateListener implements AWFEventListener {

    @Override
    public void handle(ActivitiEvent event) {
        ActivitiEntityEventImpl eventImpl = (ActivitiEntityEventImpl) event;
        TaskEntity taskEntity = (TaskEntity) eventImpl.getEntity();
        log.info(">>>>>>>>>>>>>>>>>>>>TaskCreateListener<<<<<<<<<<<<<<<<<<<<");

        log.info("create task is "+taskEntity.getName()+" key is:"+taskEntity.getTaskDefinitionKey());
        log.info("enter the task create listener ---->" + event.getType().name());



        //是否已经对任务进行了人员分配
        boolean isAssigned=false;
        //检查是否为会签任务，若是，则先从变量中获得执行人员
        ExecutionEntity execution = taskEntity.getExecution();
        log.info("当前Execution："+ execution.getId());
        if(execution.getParent()!=null && execution.getParent().isMultiInstanceRoot())
        {
            log.info("当前节点【"+execution.getCurrentFlowElement().getName()+"】为会签节点多实例生成的子节点,跳过处理");
            return;
        }
        if(!StringUtil.isNullOrEmpty(taskEntity.getAssignee()))
        {
            log.info("当前为自动发起的开始节点："+ execution.getVariableLocal("applyUserId"));
            return;
        }

        taskEntity.setAssignee("79088236-7b13-4292-9370-94ab9b8439bb");

        // execution.setVariable("assignee","79088236-7b13-4292-9370-94ab9b8439bb");
        // execution.setVariable("assigneeList", new ArrayList<String>());

        publishAssignEvent(taskEntity);

    }

    public void publishAssignEvent(TaskEntity taskEntity){
        if (!StringUtil.isNullOrEmpty(taskEntity.getAssignee())) {
            Context.getProcessEngineConfiguration().getEventDispatcher().dispatchEvent(
                    ActivitiEventBuilder.createEntityEvent(ActivitiEventType.TASK_ASSIGNED, taskEntity));
        }
    }
}
